package chances.wechat.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import chances.wechat.data.PageBean;
import chances.wechat.entity.UserCollection;
import chances.wechat.entity.UserHistory;
import chances.wechat.model.DelCollectionModel;
import chances.wechat.resp.ResultSetResponse;
import chances.wechat.utils.JSONUtils;

@Service
public class StbDataService extends BaseService {
    Logger error = LoggerFactory.getLogger("error");
    Logger logger = LoggerFactory.getLogger("stbdata");

    @Value("${send.data}")
    private String sendData;

    @Value("${epg.data.host}")
    private String epgHost;

    @Value("${connect.timeout:2}")
    private int connectTimeout;

    @Value("${read.timeout:3}")
    private int readTimeout;

    public Boolean sendToStb() {
        return sendData.equals("yes");
    }

    public void addCollection(UserCollection userCollection, String stbNo) {
        String userId = stbNo;
        String contentId = userCollection.getContentId();
        String contentType = userCollection.getContentType();
        String contentName = userCollection.getContentName();

        StringBuilder strBuild = new StringBuilder(epgHost);
        strBuild.append("/user/collection/addContent.do");
        strBuild.append("?userId=" + userId);
        strBuild.append("&contentId=" + contentId);
        strBuild.append("&contentType=" + contentType);

        try {
            contentName = URLEncoder.encode(contentName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("内容名称编码错误");
        }
        strBuild.append("&contentName=" + contentName);

        logger.info("add collection: {}", strBuild.toString());
        getMethod(strBuild.toString());
    }

    public void deleteCollection(String stbNo, List<String> codes) {
        List<DelCollectionModel> collections = new ArrayList<DelCollectionModel>();
        DelCollectionModel collection = null;
        for (String code : codes) {
            collection = new DelCollectionModel();
            collection.setUserId(stbNo);
            collection.setContentId(code);
            collections.add(collection);
        }

        StringBuilder url = new StringBuilder(epgHost);
        url.append("/user/collection/removeCollections.do");
        postMethod(url.toString(), JSONUtils.fromObject(collections));
    }

    public void emptyCollection(String stbNo) {
        // post请求发送
        StringBuilder url = new StringBuilder(
                epgHost + "/user/collection/clear.do");
        url.append("?userId=" + stbNo);
        getMethod(url.toString());
    }

    public ResultSetResponse<UserCollection> listCollection(String stbNo,
            Integer page, Integer size) {

        StringBuilder strBuilder = new StringBuilder(epgHost);
        strBuilder.append("/user/collection/list.do");
        strBuilder.append("?userId=" + stbNo);
        strBuilder.append("&pageIndex=" + page);
        strBuilder.append("&pageSize=" + size);
        String responseText = getMethod(strBuilder.toString());

        Map<String, Object> contentMap = JSONUtils.toMap(responseText);
        String total = (String) contentMap.get("total");
        String curPage = (String) contentMap.get("curpage");
        String pageSize = (String) contentMap.get("pagesize");
        PageBean pageBean = new PageBean(Integer.parseInt(total),
                Integer.parseInt(pageSize));
        pageBean.setCurrentPage(Integer.parseInt(curPage));

        @SuppressWarnings("unchecked")
        List<Map<String, String>> contentList = (List<Map<String, String>>) contentMap
                .get("collectionList");
        List<UserCollection> contents = new ArrayList<UserCollection>();
        for (Map<String, String> map : contentList) {
            UserCollection content = new UserCollection();
            content.setContentId(map.get("contentId"));
            content.setContentName(map.get("contentName"));
            content.setContentType(map.get("contentType"));
            content.setContentPoster(map.get("contentPoster"));
            contents.add(content);
        }
        return new ResultSetResponse<UserCollection>(contents, pageBean);
    }

    public void addHistory(UserHistory userHistory, String stbNo) {
        String userId = stbNo;
        String contentId = userHistory.getContentId();
        String contentType = userHistory.getContentType();
        String contentName = userHistory.getContentName();
        long elapsedTime = userHistory.getElapsedTime();
        int episodeIndex = userHistory.getEpisodeIndex();
        String programId = userHistory.getProgramId();

        StringBuilder strBuild = new StringBuilder(epgHost);
        strBuild.append("/user/history/addContent.do");
        strBuild.append("?userId=" + userId);
        strBuild.append("&contentId=" + contentId);
        strBuild.append("&contentType=" + contentType);
        try {
            contentName = URLEncoder.encode(contentName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.info("内容名称编码错误");
        }
        strBuild.append("&contentName=" + contentName);
        strBuild.append("&episodeIndex=" + episodeIndex);
        strBuild.append("&elapsedTime=" + elapsedTime);
        strBuild.append("&programId=" + programId);
        getMethod(strBuild.toString());
    }

    public void deleteHistory(String stbNo, List<String> codes) {
        List<DelCollectionModel> collections = new ArrayList<DelCollectionModel>();
        DelCollectionModel collection = null;
        for (String code : codes) {
            collection = new DelCollectionModel();
            collection.setUserId(stbNo);
            collection.setContentId(code);
            collections.add(collection);
        }

        StringBuilder url = new StringBuilder(epgHost);
        url.append("/user/history/removeHistories.do");
        postMethod(url.toString(), JSONUtils.fromObject(collections));

    }

    public void emptyHistory(String stbNo) {
        StringBuilder url = new StringBuilder(
                epgHost + "/user/history/clear.do");
        url.append("?userId=" + stbNo);
        getMethod(url.toString());
    }

    public ResultSetResponse<UserHistory> listHistory(String stbNo, Integer page, Integer size) {
        StringBuilder strBuilder = new StringBuilder(epgHost);
        strBuilder.append("/user/history/list.do");
        strBuilder.append("?userId=" + stbNo);
        strBuilder.append("&pageIndex=" + page);
        strBuilder.append("&pageSize=" + size);
        String responseText = getMethod(strBuilder.toString());

        Map<String, Object> contentMap = JSONUtils.toMap(responseText);
        String total = (String) contentMap.get("total");
        String curPage = (String) contentMap.get("curpage");
        String pageSize = (String) contentMap.get("pagesize");
        PageBean pageBean = new PageBean(Integer.parseInt(total),
                Integer.parseInt(pageSize));
        pageBean.setCurrentPage(Integer.parseInt(curPage));

        @SuppressWarnings("unchecked")
        List<Map<String, String>> contentList = (List<Map<String, String>>) contentMap
                .get("historyList");
        List<UserHistory> histories = new ArrayList<UserHistory>();
        for (Map<String, String> map : contentList) {
            UserHistory history = new UserHistory();
            history.setContentId(map.get("contentId"));
            
            history.setContentName(map.get("contentName"));
            history.setContentType(map.get("contentType"));
            history.setContentPoster(map.get("contentPoster"));
            history.setElapsedTime(Long.parseLong(map.get("elapsedTime")));
            history.setEpisodeIndex(Integer.parseInt(map.get("episodeIndex")));
            history.setProgramId(map.get("programId"));
            histories.add(history);
        }
        return new ResultSetResponse<UserHistory>(histories, pageBean);
    }

}
